<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\api\model\ProjectInfoStageRoute as ProjectInfoStageRouteModel;
use app\api\model\ProjectClassStageRoute as ProjectClassStageRouteModel;
use app\api\model\ProjectTest;
use app\api\model\User as UserModel;
use app\Request;
use think\facade\Config;
use think\Queue\Job;

class ProjectTask extends Base
{

    public function fire(Job $job, $data){

        $Project = $this->getStageCurrInfo($data['id'],$data['project_class'],strtotime($data['time']));

        if($Project){
            $dao = new ProjectClassStageRouteModel;
            $info = $dao->where('class_id','=',$data['project_class'])
                ->where('stage_id','=',$Project['id'])->find();
            $infoArray = $info->toArray();

            if($infoArray['r_ischeck']){
                //如果需要评审的话，进行信息推送
                $currTime = strtotime($data['time']); //当前时间
                $stageEndTIme = $Project['end_time']; //当前项目当前阶段的结算时间
                $stageStartTime = $Project['start_time'];

                //阶段时间结算的前7天进行提醒
                if( (($stageEndTIme-$currTime)<=604800 && $stageEndTIme-$currTime>0)  ){
                    $ProjectTest = new ProjectTest();
                    $tmp['name'] = json_encode($infoArray);
                    $tmp['ts'] = json_encode($Project);
                    $tmp['projectinfo'] = json_encode($data);
                    $tmp['project_id'] = $data['id'];
                    $tmp['time'] = time();
                    $re = $ProjectTest->insertGetId($tmp);
                    if($re){
                        //查询下项目经理的电话
                        $userdao = new UserModel();
                        $userinfo = $userdao->where('id','=',$data['project_pm'])->find();
                        $sql = $userdao->getLastSql();
                        $title="您有项目《".$data['project_name']."》需要评审，请登陆项目管理系统进行查看(测试)";
                        $content="您有项目《".$data['project_name']."》需要评审，查看步骤：打开内部门户->应用->项目管理";
                        $mobile= $userinfo['mobile'];
                        $pulish_verion =  Config::get('app.pulish_verion');
                        $pub = "";
                        $pubtoken = "";
                        if($pulish_verion == 'dev'){
                            $pub = Config::get('app.pub_dev');
                            $pubtoken = Config::get('app.pubtoken_dev');
                        }else if($pulish_verion == 'pro'){
                            $pub = Config::get('app.pub');
                            $pubtoken = Config::get('app.pubtoken');
                        }
                        $this->sendEsbMsg($title,$content,$mobile,$pub,$pubtoken);
                    }
                }

            }

        }

        $job->delete();


    }

    /**
     * 根据项目类别id获取项目阶段信息
     * @param Request $request
     * @return \think\response\Json
     */
    private function getStageCurrInfo($project_id,$class_id,$CurrTime){

        $ProjectInfoStageRouteModel= new ProjectInfoStageRouteModel;
        $list = $ProjectInfoStageRouteModel->alias('i')
            ->field('s.id,s.name,i.start_time,i.end_time,i.status')
            ->where('class_id','=',$class_id)
            ->where('start_time','<',$CurrTime)
            ->where('end_time','>',$CurrTime)
            ->where('stage_id','>',0)
            ->where('project_id',$project_id)
            ->leftjoin('project_stage s','i.stage_id = s.id')
            ->find();
        if($list){
            return($list->toArray());
        }

    }

    public function sendEsbMsg($title,$content,$mobile,$pub,$pubtoken){
        try {

            $datastr = array(
                "REQUEST"=>array(
                    "HEAD"=>array(
                        "ACCOUNT"=>"",
                        "BIZTRANSACTIONID"=> "PMS_SEND_".date("YmdHis")."_".rand(),
                        "CONSUMER"=> 1,
                        "COUNT"=> 1,
                        "MODULE"=> "",
                        "PAGENUM"=> "",
                        "PAGESIZE"=> "",
                        "PASSWORD"=> "",
                        "SRVLEVEL"=> 1
                    ),
                    "LIST"=>array(
                        "0"=>array(
                            "pub"=>"{$pub}",
                            "pubtoken"=>"{$pubtoken}",
                            "receivers"=>array(
                                "0"=>array(
                                    "telphone"=>$mobile
                                )
                            ),
                            "text"=>array(
                                "0"=>array(
                                    "context"=> $content
                                )
                            ),
                            "Title"=>$title,
                            "sendType"=>"url"
                        )
                    )
                )

            );

            $str = json_encode($datastr);
            $username = "test123";
            $password = "test123456";
            $pulish_verion =  Config::get('app.pulish_verion');
            $baseUrl = "";
            if($pulish_verion == 'dev'){
                $baseUrl = Config::get('app.esb_url_dev');
            }else if($pulish_verion == 'pro'){
                $baseUrl = Config::get('app.esb_url_pro');
            }
            $url = $baseUrl."/WP_CQP_SOA/APP_PUBLIC_SERVICES/Proxy_Services/TA_MT/MT_MSG_02_ESBsendMsg_PS";
            $res = http_request_base_auth($url,$str,$username,$password);
            return $res;

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }

    }

}
